
import CryptoJS from 'crypto-js';
import axios from 'axios';

// 腾讯云API配置
const config = {
    SecretId: 'AKIDNgplTwBCyWt3zkHagZEgvvrusdFfuxlN',
    SecretKey: 'QfldHi5Sh1EE0SjphQJBzf7MSN3LTP8d',
    Region: 'ap-guangzhou',
    Host: 'asr.tencentcloudapi.com',
    Service: 'asr',
    Version: '2019-06-14',
    Action: 'SentenceRecognition',
    Algorithm: 'TC3-HMAC-SHA256'
};

// 生成签名
function generateSignature(payload: string, timestamp: number) {
    const date = new Date(timestamp * 1000).toISOString().split('T')[0];

    // 1. 拼接规范请求串
    const httpRequestMethod = 'POST';
    const canonicalUri = '/';
    const canonicalQueryString = '';
    const canonicalHeaders = 'content-type:application/json\n' + 'host:' + config.Host + '\n';
    const signedHeaders = 'content-type;host';
    const hashedRequestPayload = CryptoJS.SHA256(payload).toString();
    const canonicalRequest = [
        httpRequestMethod,
        canonicalUri,
        canonicalQueryString,
        canonicalHeaders,
        signedHeaders,
        hashedRequestPayload
    ].join('\n');

    // 2. 拼接待签名字符串
    const credentialScope = date + '/' + config.Service + '/tc3_request';
    const hashedCanonicalRequest = CryptoJS.SHA256(canonicalRequest).toString();
    const stringToSign = [
        config.Algorithm,
        timestamp,
        credentialScope,
        hashedCanonicalRequest
    ].join('\n');

    // 3. 计算签名
    const kDate = CryptoJS.HmacSHA256(date, 'TC3' + config.SecretKey);
    const kService = CryptoJS.HmacSHA256(config.Service, kDate);
    const kSigning = CryptoJS.HmacSHA256('tc3_request', kService);
    const signature = CryptoJS.HmacSHA256(stringToSign, kSigning).toString();

    // 4. 拼接 Authorization
    return config.Algorithm + ' ' +
        'Credential=' + config.SecretId + '/' + credentialScope + ', ' +
        'SignedHeaders=' + signedHeaders + ', ' +
        'Signature=' + signature;
}

// 将音频数据转换为Base64
async function audioToBase64(audioBlob: Blob): Promise<string> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
            const base64data = (reader.result as string).split(',')[1];
            resolve(base64data);
        };
        reader.onerror = reject;
        reader.readAsDataURL(audioBlob);
    });
}

// 语音识别接口
export async function recognizeSpeech(audioBlob: Blob) {
    try {
        // 将音频转换为Base64
        const audioBase64 = await audioToBase64(audioBlob);

        const timestamp = Math.floor(Date.now() / 1000);
        const requestData = {
            EngSerViceType: "8k_zh",
            SourceType: 1,
            VoiceFormat: "wav",
            Data: audioBase64,
            DataLen: audioBase64.length,
            ProjectId: 0,
            SubServiceType: 2,
            FilterDirty: 0,
            FilterModal: 0,
            FilterPunc: 0,
            ConvertNumMode: 1
        };

        const payload = JSON.stringify(requestData);
        const authorization = generateSignature(payload, timestamp);

        // 发送请求
        const response = await axios.post('/api/asr/', payload, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authorization,
                'Host': config.Host,
                'X-TC-Action': config.Action,
                'X-TC-Region': config.Region,
                'X-TC-Timestamp': timestamp.toString(),
                'X-TC-Version': config.Version
            }
        });

        return response.data;
    } catch (error: any) {
        console.error('Speech recognition error:', error.response?.data || error);
        throw error;
    }
}